/*********************************************
Project : Test program for dosing controller
Version : 
Date    : 27-09-2006
Author  : Henning Hargaard
Company : Ingineering College of Aarhus       
Comments: 
	  STK500 setup :
	  Header "RS232 spare" connected to RXD/TXD :
	  RXD = PORTD, bit0
	  TXD = PORTD, bit1
	  (See STK500 User Guide page 3-5)

Chip type           : Mega16
Clock frequency     : 8,0000 MHz
*********************************************/

#include <mega16.h>
#include <delay.h>
#include <stdlib.h>

#include "uart.h"
#include "lcd162.h"
#include "sensor_amp.h"

// Constants
#define XTAL 8000000
#define BAUD 9600 

#define SWE PORTB.0
#define SW1 PIND.2
#define SW2 PIND.3
#define SW3 PINB.1

#define MOTOR1 PORTA.7
#define MOTOR2 PORTA.6
#define MOTOR3 PORTA.5
#define MOTOR4 PORTA.4
#define MOTOR5 PORTA.3

#define MOTOR MOTOR4

#define BUZZER PORTD.7 

#define PWM PORTD.5 

#define ADSC ADCSRA.6

// Sends ASCII string til UART (value of int i)
/* void DispInteger( int i )
{
char nummer[7];

  itoa( i, nummer ); 
  SendStringSRAM( nummer );
} */

void main(void)
{
unsigned int tara;
                 
  // 9600 baud, 8 databit, no parity
  InitUART(BAUD,XTAL,8,0);
  // Initialize lcd display
  LCDInit();
  LCDDispStrFLASH("Henning Hargaard");
  LCDGotoXY(0,1);
  LCDDispStrFLASH("Thyvej 24");
  
  // Initialize sensor amplifier
  sensorInit();
  // Sensor amplifier : First stage gain ~ 5
  setFirstStageGain(60);
  // Sensor amplifier : Second stage gain = 200
  setSecondStageGain(7);
  // Sensor amplifier : Offset = 0 volt
  setOutputOffset(250); 

  DDRA = 0b11111110;
  PORTA &= 0b00000111;
  
  DDRB.7 = 1;
  DDRB.4 = 1;
  DDRB.3 = 1;
  DDRB.2 = 1;
  DDRB.0 = 1;
  
  DDRD.5 = 1;
  PWM = 1; 
  //MOTOR = 1;
 
  SWE = 1;
  
   // External AREF reference, ADLAR = 0, Input = ADC0 single ended
  ADMUX = 0b00000000;

  // ADC enable
  // Start conversion
  // ADC interrupt disabled
  // ADC prescaler = 64 (=> ADC clock = 8 MHz / 64 = 125 kHZ)
  // OBS : Bit ADATE = 1 => "Auto triggering" enabled.
  ADCSRA = 0b11100110;
  // "Trigger Source" = "Free Running Mode"
  SFIOR = 0b00000000;
  // Start first AD conversion (then the ADC is free running)
  ADSC = 1;
   
  while (1)
  {
     delay_ms(500);
     //MOTOR = !MOTOR;
     // Read and display ADC
     LCDClear();
     if (SW1)
       tara = 1000-ADCW;
     LCDDispInteger(1000-ADCW-tara);  
     // Send Carrage return to UART
     // SendChar(0x0D);
     // BUZZER = !BUZZER; 
  }
}